package service;

import model.Todo;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TodoService {
    public void save(String todo) throws SQLException {
        String sql = "INSERT INTO todo_list (todo) VALUES (?)";

        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, todo);

                s.executeUpdate();
            }
        }
    }

    public List<Todo> query() throws SQLException {
        List<Todo> todoList = new ArrayList<>();
        String sql = "SELECT id, todo, done FROM todo_list ORDER BY id";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement s = c.prepareStatement(sql)) {
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        Todo todo = new Todo();
                        todo.id = rs.getInt("id");
                        todo.todo = rs.getString("todo");
                        todo.done = rs.getBoolean("done");
                        todoList.add(todo);
                    }
                }
            }
        }
        return todoList;
    }
}
